<template>
  <div>
    <el-button
      v-if="addRow"
      size="mini"
      @click="dataSource.push({})"
    >
      添加
    </el-button>
    <el-table :data="dataSource">
      <el-table-column v-for="(item, index) of tableProps" :key="index" :label="item.label" :prop="item.index" :width="itemWidth(item.minWidth, item.type)">
        <template slot-scope="scope">
          <!-- 根据类型渲染 只读 多选 下拉框 输入框 -->
          <dync-control
            v-model="dataSource[scope.$index][item.index]"
            :types="item.type"
            :config="item.config"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <slot slot-scope="scope" :row="scope">
          <el-button
            size="mini"
            @click="handleInsertRow(scope.$index)"
          >
            插入
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleRemoveConf(scope.$index)"
          >
            删除
          </el-button>
        </slot>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import './dync'

export default {
  props: {
    tableProps: {
      type: Array,
      required: true
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    dataSource: {
      type: Array,
      default: () => []
    },
    addRow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      //
      removeIds: []
    }
  },
  methods: {
    // 列宽
    itemWidth(minWidth, type) {
      const defaultWidth = '70px'
      // 单选框时
      if (type === 'checkbox' || (typeof minWidth === 'boolean' && minWidth)) {
        return defaultWidth
      }
      return minWidth
    },
    handleRemoveConf(index) {
      const key = this.dataSource[index][this.rowKey]
      if (key) {
        this.removeIds.push(key)
        this.$emit('removeRow', key)
      }
      this.dataSource.splice(index, 1)
    },
    handleInsertRow(index) {
      this.dataSource.splice(index + 1, 0, {})
      this.$emit('insertRow')
    }
  }
}
</script>
